package com.macbulldev.poc.testgin.controller;

import java.util.Date;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import net.youngdev.util.encryption.MD5Util;

import org.apache.log4j.Logger;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.macbulldev.poc.testgin.service.WebappUtils;
import com.macbulldev.poc.testgin.domain.AppUser;
import com.macbulldev.poc.testgin.domain.EventLog;



@org.springframework.stereotype.Controller
public class MyAccountController {
	private static final Logger LOGGER = Logger.getLogger(MyAccountController.class);

//	@Autowired
//	@Qualifier("schedulerFactory")
//	private SchedulerFactoryBean schedulerFactory;

	@RequestMapping(value = {"/myacct/password/change"},method=RequestMethod.GET) 
    public String renderChangePassword( ModelMap modelMap,Model model) {
		
		
		model.addAttribute("currentError","");
		model.addAttribute("confirmError","");
		model.addAttribute("sizeError","");
		model.addAttribute("successMsg","");
		
        return "myacct/passwordchange";
    }
	
	
		
	
	
	@RequestMapping(value = {"/myacct/password/change"},method=RequestMethod.POST) 
    public String processChangePassword(@RequestParam("oldPassword") String oldPass,
    		@RequestParam("newPassword") String newPass,
    		@RequestParam("confirmPassword") String confirmPass,
    		HttpSession httpSession,
    		Model model)
	{
		
		
		
		
		SecurityContext springSecurityContext = (SecurityContext)httpSession.getAttribute("SPRING_SECURITY_CONTEXT");
		String email = ((AppUser)springSecurityContext.getAuthentication()).getEmail();
		
		Boolean error = false;
		
		AppUser myUser = AppUser.getByEmail(email);
		
		if (!myUser.getPassword().equals(MD5Util.getMD5Base64WithLabel(oldPass)))
		{
			model.addAttribute("currentError","Error: Could not Match user with Current Password Input");
			error = true;
		}
		if(!newPass.equals(confirmPass))
		{
			model.addAttribute("confirmError","Error: Password Confirmation Failed, New and Confirm Fields Do Not Match");
			error = true;
		}
		if(newPass.length() < 8){
			
			error = true;
			model.addAttribute("sizeError","Error: Minimum Character Length Failed - Minimum 8 Characters");
		}
		
		if(!error)
		{
			
			myUser.setPassword((MD5Util.getMD5Base64WithLabel(newPass)));
			myUser.merge();
			model.addAttribute("successMsg","Your Password Has Been Updated.");
		}
	    
		return "myacct/passwordchange";
   
    }
	
	
	@RequestMapping(value = {"/myacct/profile"},method=RequestMethod.GET) 
    public String renderProfile(HttpSession session,
    		Model model)
	{
		
		
	AppUser user = WebappUtils.getAuthenticationObject(session);
	 model.addAttribute("appUser",user);
	    
		return "myacct/profile";
   
    }
	
	@RequestMapping(value = {"/myacct/accept_security"},method=RequestMethod.GET) 
    public String acceptSecurity(@RequestParam("agreed") Boolean agreed, HttpSession session, 
    		Model model)
	{
		LOGGER.debug("Accept security :" +agreed);
		AppUser user =WebappUtils.getAuthenticationObject(session);
		if (user != null && agreed != null && agreed)
		{
			EventLog log = new EventLog();
			log.setCreateTs(new Date());
			log.setCreateUsername(user.getEmail());
			log.setObjectClass(user.getClass().getName());
			log.setOperation("Agreed to security notice");
			log.persist();

			user.addRole("SECURITYAGREEMENT");

			LOGGER.error("Email "+user.getEmail());
		}
	    
		return "redirect:/";
   
    }
	
	@RequestMapping(value = {"/myacct/securityagreement/form"},method=RequestMethod.GET) 
    public String renderSecurityForm(HttpSession session, 
    		Model model)
	{
		try{
		AppUser user =WebappUtils.getAuthenticationObject(session);
		if (user != null)
		{
			LOGGER.error("Email "+user.getEmail());
		}
		}
		catch (Exception e)
		{
			LOGGER.debug("Error:",e);
		}
	    
		return "myacct/securityagreement_form";
   
    }
	
	@RequestMapping(value = {"/has_securityagreement"},method=RequestMethod.GET) 
    public String hasSecurityAgreement(HttpSession session,
    		Model model)
	{
		
		LOGGER.error("Email"+((SecurityContext)session.getAttribute("SPRING_SECURITY_CONTEXT")).getAuthentication().getPrincipal());
	
	    
		return "index";
   
    }
	
	
	
	@RequestMapping(value = "/myacct/{email}/update", method = RequestMethod.GET)    
    public String updateForm(@PathVariable("email") String email, ModelMap model) 
	{    
		
        if (email == null) throw new IllegalArgumentException("An Identifier is required");        
        model.addAttribute("appUser", AppUser.getByEmail(email));                
        return "myacct/update";        
    }
	
	@RequestMapping(value="/myacct/{email}/update",method = RequestMethod.POST)  
    public String update(@PathVariable("email") String email,
    		@RequestParam(value="selectedRoles", required=false) String[] roleStrings,
    		@Valid @ModelAttribute("appUser") AppUser appUser, 
    		BindingResult result, 
    		Model model) throws SchedulerException 
	{   
		
		appUser.merge();
    		
    		
    	return "redirect:/appuser/"+appUser.getEmail()+"/show";    
    	
    }
		
	
	
	
	
}
